<template>
    <el-row class="login-container" justify="center" :align="'middle'">
        <el-card style="max-width: 480px">
            <!-- 插槽 -->
            <template #header>
                <div class="card-header">
                    <img :src="imgUrl" alt="">
                </div>
            </template>
            <div class="jump-link">
                <el-link type="primary" @click="handleChange">{{ formType ? '返回登录' : '注册账号' }}</el-link>
            </div>
            <el-form :model="loginForm" ref="loginFormRef" style="max-width: 600px;" class="demo-ruleForm"
                :rules="rules">
                <el-form-item prop="userName">
                    <el-input v-model="loginForm.userName" placeholder="请输入手机号" :prefix-icon="UserFilled">
                    </el-input>
                </el-form-item>
                <el-form-item prop="passWord">
                    <el-input v-model="loginForm.passWord" type="password" placeholder="请输入密码" :prefix-icon="Lock">
                    </el-input>
                </el-form-item>
                <!-- 如果是登录表单，显示验证码 -->
                <el-form-item v-if="formType" prop="validCode">
                    <el-input v-model="loginForm.validCode" placeholder="请输入验证码" :prefix-icon="Lock">
                        <template #append>
                            <span @click="countdownChange">{{ countdown.validText }}</span>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :style="{ width: '100%' }" @click="submitForm(loginFormRef)">
                        {{ formType ? '注册账号' : '登录' }}
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </el-row>
</template>
<script setup>
// ref用于将基本数据类型（如数字、字符串、布尔值等）转换为响应式对象，确保数据变化时能触发视图更新。
// reactive用于将一个对象转换为响应式对象，确保对象的属性变化时能触发视图更新。
import { ref, reactive, computed, toRaw } from 'vue';
import { ElMessage } from 'element-plus'
import { getCode, userAuthentication, login, menuPermissions } from '../../api/index'
import { UserFilled, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore()
const imgUrl = new URL('../../../public/login-head.png', import.meta.url).href
// 切换表单，0是登录，1是注册
const formType = ref(0)
const routerList = computed(() => store.state.menu.routerList)
// 表单校验规则
const validateUser = (rule, value, callback) => {
    // 不能为空
    if (value === '') {
        callback(new Error('请输入账号'))
    } else {
        const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
        phoneReg.test(value) ? callback() : callback(new Error('手机号格式不对，请输入正确的手机号'))
    }
}
// 密码校验
const validatePass = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else {
        const passReg = /^[a-zA-Z0-9_-]{4,16}$/
        passReg.test(value) ? callback() : callback(new Error('密码长度4-16位'))
    }
}
// 表单校验
const rules = reactive({
    userName: [{ validator: validateUser, trigger: 'blur' }],
    passWord: [{ validator: validatePass, trigger: 'blur' }]
})
// 点击切换登录和注册
const handleChange = () => {
    formType.value = formType.value ? 0 : 1
}
// 定义登录表单数据
const loginForm = reactive({
    userName: '',
    passWord: '',
    validCode: ''
})

// 发送短信
const countdown = reactive({
    validText: '获取验证码',
    time: 60
})
let flag = false
const countdownChange = () => {
    // 倒计时定时器
    // 如果已发送就不处理
    if (flag) return

    // 判断手机号是否正确
    const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    if (!loginForm.userName || !phoneReg.test(loginForm.userName)) {
        return ElMessage({
            message: '请输入正确的手机号',
            type: 'warning'
        })

    }
    // 验证码定时
    const time = setInterval(() => {
        if (countdown.time <= 0) {
            countdown.time = 60
            countdown.validText = '获取验证码'
            flag = false
            //  清除倒计时
            clearInterval(time)
        } else {
            countdown.time -= 1
            countdown.validText = `剩余${countdown.time}s`
        }
    }, 1000)
    flag = true
    getCode({ tel: loginForm.userName }).then(({ data }) => {
        if (data.code === 10000) {
            ElMessage.success('发送成功')
        }
    })
}

const router = useRouter()

const loginFormRef = ref()
// 表单提交   async异步函数
const submitForm = async (formEl) => {
    console.log('submitForm called');
    if (!formEl) return
    //  手动触发校验
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 注册页面
            if (formType.value) {
                userAuthentication(loginForm).then(({ data }) => {
                    console.log('API response:', data); // 添加这行
                    if (data.code === 10000) {
                        ElMessage.success('注册成功，请登录')
                        formType.value = 0
                    }
                })
            } else {
                // 登陆页面
                login(loginForm).then(({ data }) => {
                    if (data.code === 10000) {
                        ElMessage.success('登录成功')
                        console.log(data, 'data')
                        //跳转
                        // 将token和用户信息缓存到浏览器
                        localStorage.setItem('pz_token', data.data.token)
                        localStorage.setItem('pz_userInfo', JSON.stringify(data.data.userInfo))
                        menuPermissions().then(({ data }) => {
                            // 处理动态路由
                            store.commit('dynamicMenu', data.data)
                            // 将响应式数据转换为普通的路由数剧
                            toRaw(routerList.value).forEach(item => {
                                router.addRoute('main',item)
                            })
                            router.push('/')
                        })

                    }
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })

}
</script>
<style lang="less" scoped>
:deep(.el-card__header) {
    padding: 0
}

.login-container {
    height: 100%;

    .card-header {
        background-color: #899fe1;

        img {
            width: 430px;
        }
    }

    .jump-link {
        text-align: right;
        margin-bottom: 10px;
    }
}
</style>